package com.varian.security.handler;

import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.varian.mybatis.handler.MybatisMetaObjectHandler;
import com.varian.security.model.SecurityEntity;
import com.varian.security.util.SecurityUtil;
import org.apache.ibatis.reflection.MetaObject;

/**
 * @author ben
 * @since 2024/6/24
 */
public class SecurityMetaObjectHandler implements MybatisMetaObjectHandler {

    private final String CREATE_ID = LambdaUtil.getFieldName(SecurityEntity::getCreateId);
    private final String UPDATE_ID = LambdaUtil.getFieldName(SecurityEntity::getUpdateId);

    @Override
    public void insertFill(MetaObject metaObject, MetaObjectHandler handler) {
        if (ObjUtil.isNull(metaObject.getValue(CREATE_ID)) && SecurityUtil.getUserId() != null) {
            handler.strictInsertFill(metaObject, CREATE_ID, Long.class, SecurityUtil.getUserId());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject, MetaObjectHandler handler) {
        if (ObjUtil.isNull(metaObject.getValue(UPDATE_ID)) && SecurityUtil.getUserId() != null) {
            handler.strictUpdateFill(metaObject, UPDATE_ID, Long.class, SecurityUtil.getUserId());
        }
    }
}
